const express = require('express')
const router = express.Router()
const fs = require('fs')
const path = require('path')
const axios = require('axios')
const config = require('./config');
var FormData = require('form-data')
const multipart = require('connect-multiparty')
var auth = require('./rights/authentication');
const multipartMiddleware = multipart()
const uploadUrl = config.serverUrl_BI + '/biEtlDbFile/upload'

/* upload */
router.post('/data', multipartMiddleware,async (req, res, next) => {
  console.log('======開始上传=======')

  let {tenantId,tenantCode,userId} = req.headers.user;

  const formData = new FormData()
  const params = req.body
  for (const key in params) {
    if (params.hasOwnProperty(key)) {
      const value = params[key]
      formData.append(key, value)
    }
  }
  const files = req.files
  if (!Object.keys(files).length) return res.send({ msg: '请选择文件' })
  for (const key in files) {
    if (files.hasOwnProperty(key)) {
      const item = files[key]
      const { path: filePath, originalFilename } = item
      const newPath = path.join(path.dirname(filePath), originalFilename) // 得到newPath新地址用于创建读取流
      fs.rename(filePath, newPath, async (err) => {
        if (err) return
        formData.append('tenantId',tenantId);
        formData.append('tenantCode',tenantCode);
        formData.append('operator',userId);
        formData.append('file',  fs.createReadStream(newPath));
        var config = {
          method: 'post',
          url: uploadUrl,
          headers: {
            'x-bdh-tenant-code': tenantCode,
            'Content-Type': 'multipart/form-data',
            'Cookie': 'lang=cn',
            ...formData.getHeaders()
          },
          data : formData,
          timeout: 600000,
          maxContentLength: Infinity,
          maxRedirects: 5
        };
        axios(config)
          .then(function (response) {
            console.log('======上传成功=======')
            res.send(JSON.stringify(response.data));
          })
          .catch(function (error) {
            console.log('======上传失敗=======')
            console.log(error);
          });
      })
    }
  }
})
/**================================================== */

module.exports = router